package com.usian.controller;

import com.usian.pojo.User;
import com.usian.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RequestMapping("/user")
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    private final static Logger logger = LoggerFactory.getLogger(UserController.class);


    @RequestMapping("/insertUser")
    public  String insertUser(User user, HttpServletRequest request, HttpServletResponse response){
        logger.info("========保存controller",user.getUserId());
        userService.insertUser(user);
        try {
            response.sendRedirect(request.getContextPath()+"findList");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "index";

    }

    @RequestMapping("/toUser")
    public  String toUser(){
        return "addUser";

    }
    @RequestMapping("/findList")
    public String findList(Model model){

        List<User> userList = userService.findList();
        model.addAttribute("userList",userList);

        return "index";
    }

    @RequestMapping("/delete")
    public  String delete(Integer userId, HttpServletRequest request, HttpServletResponse response){
        userService.delete(userId);
        try {
            response.sendRedirect(request.getContextPath()+"findList");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "index";

    }

    @RequestMapping("/findByid")
    public  String findByid(Integer userId,Model model){
      User user=  userService.findByid(userId);
    model.addAttribute("user",user);
        return "update";

    }


    @RequestMapping("update")
    public String update(User user,Model model){
        userService.update(user);
        return this.findList(model);
    }


}
